//
//  LJPictureSelectViewController.swift
//  图片选择器
//
//  Created by Raymond on 15/12/30.
//  Copyright © 2015年 liu. All rights reserved.
//

import UIKit

class LJPictureSelectViewController: UICollectionViewController {
    /// 布局属性
    private var layout = UICollectionViewFlowLayout()
    /// 重写标示
    private let reuseIdentifier = "ReuseIdentifier"
    /// 图片数组
    var pictures = [UIImage]()
    /// 图片最大的数量
    private var maxCount = 6
    /// 最近点击的indexpath选项
    private var currentIndexPath: NSIndexPath?
    
    init() {
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        prepareCollectionView()
    }
    
    private func prepareCollectionView() {
        // 注册cell
        collectionView?.registerClass(LJPictureSelectViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        // 设置背景色
        collectionView?.backgroundColor = UIColor.whiteColor()
        // 设置大小
        layout.itemSize = CGSize(width: 80, height: 80)
        // 设置分组边距
        layout.sectionInset = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
    }
}

// MARK: - 分类
extension LJPictureSelectViewController: LJPictureSelectViewCellDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictures.count < maxCount ? pictures.count+1 : maxCount
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! LJPictureSelectViewCell
        
        // 指定cell的代理
        cell.delegate = self
        
        if indexPath.item < pictures.count {
            cell.image = pictures[indexPath.item]
        }else{
            cell.setAddButton()
        }
//        cell.image = pictures[indexPath.item]

        return cell
    }
    
    // MARK: - cell代理方法
    func pictureSelectViewAddButtonDidClick(cell: LJPictureSelectViewCell) {
        // 保存indexpath
        currentIndexPath = collectionView?.indexPathForCell(cell)
        // 判断系统的相册是否可用
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            print("系统相册不可用")
            return
        }
        // 创建系统的照片选择器
        let picturePicker = UIImagePickerController()
        // 设置代理
        picturePicker.delegate = self
        // 当初系统的照片选择控制器
        self.presentViewController(picturePicker, animated: true, completion: nil)
    }
    
    func pictureSelectViewRemoveButtonDidClick(cell: LJPictureSelectViewCell) {
        // 获取点击的indexpath
        let indexPath = collectionView?.indexPathForCell(cell)
        pictures.removeAtIndex(indexPath!.item)
        collectionView?.reloadData()
    }
    
    // MARK: - 系统照片选择控制器代理
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        let newImage = image.scaleImage()
        // 判断点击的时加号按钮还是图片
        if currentIndexPath!.item == pictures.count {
            // 表示点击的时加号按钮
            pictures.append(newImage)
        }else{
            // 表示点击的是图片
            pictures[currentIndexPath!.item] = newImage
        }
        collectionView?.reloadData()
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
}

/// 协议
@objc protocol LJPictureSelectViewCellDelegate: NSObjectProtocol {
    /// 加号按钮被点击
    optional func pictureSelectViewAddButtonDidClick(cell: LJPictureSelectViewCell)
    
    /// 删除按钮被点击
    optional func pictureSelectViewRemoveButtonDidClick(cell: LJPictureSelectViewCell)
}

// MARK: - 自定义cell
class LJPictureSelectViewCell: UICollectionViewCell {
    
    // 图片属性
    var image: UIImage? {
        didSet{
            addButton.setImage(image, forState: UIControlState.Normal)
            // 隐藏删除按钮
            removeButton.hidden = false
        }
    }
    
    /// 代理
    weak var delegate: LJPictureSelectViewCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        prepareUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 设置加号图片的方法
    func setAddButton() {
        addButton.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        removeButton.hidden = true
    }
    
    private func prepareUI() {
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        addButton.translatesAutoresizingMaskIntoConstraints = false
        removeButton.translatesAutoresizingMaskIntoConstraints = false
        
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ab": addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[ab]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["ab": addButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:[rb]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["rb": removeButton]))
        contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[rb]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["rb": removeButton]))
    }
    // MARK: - 按钮点击事件
    @objc private func addPicture() {
        delegate?.pictureSelectViewAddButtonDidClick?(self)
    }
    
    @objc private func removePicture() {
        delegate?.pictureSelectViewRemoveButtonDidClick?(self)
    }
    
    // MARK: - 懒加载
    /// 添加图标
    private lazy var addButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "compose_pic_add_highlighted"), forState: UIControlState.Highlighted)
        button.addTarget(self, action: "addPicture", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    /// 删除按钮
    private lazy var removeButton: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        button.addTarget(self, action: "removePicture", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
}
